<template>
  <PageContainer>
    <view class="container">
      <Header title="报名信息" />
      <BasicsForm @register="formRegister" />
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* activityRegisterForm 报名信息 */
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import { useForm } from '@/components/Form';
  import { onLoad } from '@/router';
  import {
    activityRegisterFormInfo,
    activityRegisterFormItem,
    registerPayFormInfo,
  } from '@/api/activity';
  import { ref } from 'vue';
  import { localDataMapping } from '@/components/Form/hooks/useForm';
  import type { ActivityRegisterForm } from '@/router/types/modules';
  import type { FormItemResult } from '@/api/membership/formCompTypes';
  import { isArray } from 'lodash-es';
  import type { customFormUserAnswerList } from '@/api/membership/types';
  import { isArrayString } from '@/utils/is';
  import { IsInternalInterfaceEnum } from '@/enums/formEnum';
  import { memberTypeGetList } from '@/api/membership';
  import dictionary from '@/utils/dictionary';

  const dataId = ref<number>();
  const activityId = ref<number>();
  const dataType = ref<ActivityRegisterForm['type']>('order');

  onLoad<'activityRegisterForm'>(async (op) => {
    dataId.value = op.id;
    activityId.value = op.activityId;
    dataType.value = op.type;
  });

  const [register, { appendSchemaByField, updateSchema }] = useForm({
    labelAlign: 'left',
    labelPosition: 'top',
    validateTrigger: 'submit',
    labelWidth: 'auto',
  });

  async function formRegister(e: any) {
    register(e);
    if (!dataId.value) return;
    if (dataType.value === 'order') {
      const res = await registerPayFormInfo(dataId.value);
      handleAppend(res.activityFormItemMap[0], res.answerList || []);
    }

    if (dataType.value === 'registerDetail') {
      const res = await activityRegisterFormInfo(dataId.value);
      handleAppend(res.activityFormItemMap[0], res.answerList || []);
    }

    if (dataType.value === 'activityManage') {
      const res = await activityRegisterFormItem({
        activityId: activityId.value as number,
        activityRegisterId: dataId.value,
      });
      handleAppend(res.activityFormItemMap[0], res.activityFormUserAnswerList || []);
    }
  }

  interface dataListItem {
    type: string;
    field: string;
  }
  const typeDataName = ref<dataListItem[]>([]);
  const dictDataName = ref<dataListItem[]>([]);

  function handleAppend(
    activityFormItemMap: FormItemResult[],
    answerList:
      | {
          formItemId: number;
          content: string[];
        }[]
      | customFormUserAnswerList[],
  ) {
    activityFormItemMap.forEach((v) => {
      const field = v.id.toString();
      if (v.isInternalInterface === IsInternalInterfaceEnum.CLASSIFICATION && v.type)
        typeDataName.value.push({ field, type: v.type });
      if (v.isInternalInterface === IsInternalInterfaceEnum.DICTIONARY && v.type)
        dictDataName.value.push({ field, type: v.type });
      const answer = answerList.find((answer) => answer.formItemId === v.id);
      const content = isArray(answer?.content) ? JSON.stringify(answer?.content) : answer?.content;
      const val = content && isArrayString(content) ? content : '';

      appendSchemaByField({
        field,
        label: v.showName,
        component: v.itemType,
        dataType: v.dataType,
        dynamicDisabled: true,
        defaultValue: v.itemDefault || val,
        required: false,
        isInternalInterface: v.isInternalInterface,
        ifShow(renderCallbackParams) {
          if (dataType.value === 'activityManage') return true;
          if (isArray(v.itemRelevanceAnsweIds)) {
            const values = renderCallbackParams.values;
            return Object.values(values).some((val) => {
              return !!v.itemRelevanceAnsweIds?.find((id) => id == val);
            });
          }
          return true;
        },
        componentProps: {
          placeholder: v.value,
          limit: v.length,
          itemDefault: v.itemDefault,
          enableValue: v.enableValue,
          localdata: localDataMapping(v.customFormItemAnswerList, {
            label: 'words',
            value: 'id',
          }),
        },
      });
    });

    getLocaldata();
  }

  async function getLocaldata() {
    const td = typeDataName.value;
    const dd = dictDataName.value;
    if (td.length) {
      const res = await memberTypeGetList(td.map((v) => v.type));
      for (let index = 0; index < td.length; index++) {
        const item = td[index];
        updateSchema({
          field: item.field,
          componentProps: {
            localdata: localDataMapping(res[item.type], { label: 'name', value: 'id' }),
          },
        });
      }
    }
    if (dd.length) {
      const dictList = await dictionary.getMulti(dd.map((v) => v.type));
      for (let index = 0; index < dd.length; index++) {
        const item = dd[index];
        updateSchema({
          field: item.field,
          componentProps: {
            localdata: localDataMapping(dictList[item.type], {
              label: 'dictLabel',
              value: 'dictValue',
            }),
          },
        });
      }
    }
  }
</script>

<style lang="scss" scoped></style>
